package com.lagou.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.sql.SQLException;

/**
 * 事务管理工具类，包含：开启事务，提交事务，回滚事务，释放资源   通知类
 */
@Component("transactionManager")
public class TransactionManager {
    @Autowired
    private ConnectionUtils connectionUtils;
    /**
     * 开启事务
     */
    public void beginTransaction(){
        try {
            // 改为手动提交事务
            connectionUtils.getThread().setAutoCommit(false);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 提交事务
     */
    public void commit(){
        try {
            connectionUtils.getThread().commit();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    /**
     * 回滚事务
     */
    public void rollback(){
        try {
            connectionUtils.getThread().rollback();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    /**
     * 释放资源
     */
    public void close(){
        try {
            // 改为自动提交事务
            connectionUtils.getThread().setAutoCommit(true);
            // 归还到连接池
            connectionUtils.getThread().close();
            // 解除线程和连接对象的绑定
            connectionUtils.removeThreadConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
